package com.jiemengshi.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.jiemengshi.server.model.DreamRecord;
import com.jiemengshi.server.model.DreamReply;
import com.jiemengshi.server.service.WechatDreamService;
import com.jiemengshi.server.service.WechatUserService;
import com.jiemengshi.server.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by MingQi on 2017/10/14.
 */
@Controller
@RequestMapping(value = {"/wechat/dream"}, produces = {"application/json;charset=UTF-8"})
public class WechatDreamController {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WechatUserService userService;
    
    @Autowired
    private WechatDreamService dreamService;
    
    @ResponseBody
    @RequestMapping("/analyze")
    public String analyzeDream(HttpServletRequest request, String keyWord){
        try {
            if(StringUtil.isEmpty(keyWord))
                throw new PrjException(ErrorCodeMsg.DREAM_ANALYZE_KEYWORD_EMPTY);

            return ApiResult.writeData(dreamService.analyzeDream(keyWord));
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/record/add")
    public String addDreamRecord(HttpServletRequest request, DreamRecord dreamRecord, String formId){
        try {
            if(StringUtil.isEmpty(dreamRecord.getTitle()))
                throw new PrjException(ErrorCodeMsg.DREAM_RECORD_TITLE_ERROR);

            if(StringUtil.isEmpty(dreamRecord.getContent()) && (dreamRecord.getVoiceRecordId() == null || dreamRecord.getVoiceRecordId() < 1))
                throw new PrjException(ErrorCodeMsg.DREAM_RECORD_CONTENT_ERROR);

            int userId = userService.getLoginUserId(request);
            dreamRecord.setWechatUserId(userId);
            
            if(dreamService.addDreamRecord(dreamRecord)) {
                userService.addFormId(userId, formId);
                return ApiResult.SUCCESS;
            } else
                throw new PrjException(ErrorCodeMsg.DREAM_RECORD_ADD_FAIL);
        } catch (PrjException e){
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error("Error message : " + e.getErrMsg());
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/record/update")
    public String updateDreamRecord(HttpServletRequest request, DreamRecord dreamRecord, String formId){
        try {
            if(StringUtil.isEmpty(dreamRecord.getTitle()))
                throw new PrjException(ErrorCodeMsg.DREAM_RECORD_TITLE_ERROR);

            if(StringUtil.isEmpty(dreamRecord.getContent()))
                throw new PrjException(ErrorCodeMsg.DREAM_RECORD_CONTENT_ERROR);
            
            if(dreamRecord.getId() < 1)
                throw new PrjException(ErrorCodeMsg.DREAM_RECORD_ID_ERROR);

            int userId = userService.getLoginUserId(request);
            dreamRecord.setWechatUserId(userId);

            if(dreamService.updateDreamRecord(dreamRecord)) {
                userService.addFormId(userId, formId);
                return ApiResult.SUCCESS;
            } else
                throw new PrjException(ErrorCodeMsg.DREAM_RECORD_UPDATE_FAIL);
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/record/get")
    public String getDreamRecord(HttpServletRequest request, int recordId){
        try {
            if(recordId < 1)
                throw new PrjException(ErrorCodeMsg.DREAM_RECORD_ID_ERROR);

            DreamRecord record = dreamService.getDreamRecordById(recordId);
            if (record != null) {
                List<DreamReply> replies = dreamService.getDreamReplyByRecordId(recordId);
                dreamService.resetDreamRecordNewReply(recordId);

                JSONObject ret = new JSONObject();
                ret.put("record", record);
                ret.put("replies", replies);

                return ApiResult.writeData(ret);
            } else
                throw new PrjException(ErrorCodeMsg.DREAM_RECORD_ID_ERROR);
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/record/delete")
    public String deleteDreamRecord(HttpServletRequest request, int recordId){
        try {
            if(recordId < 1)
                throw new PrjException(ErrorCodeMsg.DREAM_RECORD_ID_ERROR);

            if (dreamService.deleteDreamRecordById(recordId))
                return ApiResult.SUCCESS;
            else
                throw new PrjException(ErrorCodeMsg.OPERATION_FAIL);
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/record/help")
    public String helpDreamRecord(HttpServletRequest request, int recordId){
        try {
            if(recordId < 1)
                throw new PrjException(ErrorCodeMsg.DREAM_RECORD_ID_ERROR);

            if (dreamService.dreamNeedHelp(recordId))
                return ApiResult.SUCCESS;
            else
                throw new PrjException(ErrorCodeMsg.OPERATION_FAIL);
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }
    
    @ResponseBody
    @RequestMapping("/reply/delete")
    public String deleteDreamReply(HttpServletRequest request, int replyId){
        try {
            if(replyId < 1)
                throw new PrjException(ErrorCodeMsg.DREAM_RECORD_ID_ERROR);

            if (dreamService.deleteDreamReplyById(replyId))
                return ApiResult.SUCCESS;
            else
                throw new PrjException(ErrorCodeMsg.DREAM_REPLY_DELETE_ERROR);
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/reply/add")
    public String addDreamReply(HttpServletRequest request, DreamReply reply, String formId){
        try {
            if(reply.getDreamRecordId() < 1)
                throw new PrjException(ErrorCodeMsg.DREAM_RECORD_ID_ERROR);
            
            if(StringUtil.isEmpty(reply.getContent()))
                throw new PrjException(ErrorCodeMsg.DREAM_REPLY_CONTENT_ERROR);

            if (dreamService.addDreamReply(reply)) {
                userService.addFormId(userService.getLoginUserId(request), formId);
                return ApiResult.SUCCESS;
            } else {
                throw new PrjException(ErrorCodeMsg.DREAM_REPLY_ADD_ERROR);
            }
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }
    
    @ResponseBody
    @RequestMapping("/record/list")
    public String listDreamRecord(HttpServletRequest request,
                                  @RequestParam(required = false, defaultValue = "0") int start,
                                  @RequestParam(required = false, defaultValue = "10") int limit){
        try {
            int userId = userService.getLoginUserId(request);
            
            if(start == 0)
                return ApiResult.writeData(dreamService.getDreamRecordByUserId(userId, start, limit), dreamService.countDreamRecordByUserId(userId));
            else
                return ApiResult.writeData(dreamService.getDreamRecordByUserId(userId, start, limit));
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/record/search")
    public String searchDreamRecord(HttpServletRequest request,
                                    @RequestParam String title,
                                  @RequestParam(required = false, defaultValue = "0") int start,
                                  @RequestParam(required = false, defaultValue = "10") int limit){
        try {
            if(StringUtil.isEmpty(title))
                throw new PrjException(ErrorCodeMsg.DREAM_RECORD_TITLE_ERROR);
            
            int userId = userService.getLoginUserId(request);

            if(start == 0)
                return ApiResult.writeData(dreamService.getDreamRecordByTitle(userId, title, start, limit), dreamService.countDreamRecordByTitle(userId, title));
            else
                return ApiResult.writeData(dreamService.getDreamRecordByTitle(userId, title, start, limit));
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/announcement/list")
    public String listAnnouncement(){
        try {
            return ApiResult.writeData(dreamService.listAnnouncement());
        } catch (Exception e) {
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/news/link")
    public String getMainPageNewsLink(){
        try {
            return ApiResult.writeData(dreamService.getMainPageNewsLink());
        } catch (Exception e) {
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/link/range")
    public String listLinkByRange(int low, int high){
        try {
            return ApiResult.writeData(dreamService.getLinksByRange(low, high));
        } catch (Exception e) {
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/voice/count")
    public String countCurrentDayVoiceRecord(HttpServletRequest request){
        try {
            return ApiResult.writeData(dreamService.countCurrentDayVoiceRecord(userService.getLoginUserId(request)));
        } catch (Exception e) {
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }
}
